<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_ad extends discuz_table
{
	public function __construct() {

		$this->_table ='er_gridad';
		$this->_pk    = 'id';

		parent::__construct();
	}
	
	/**
	 * 获取广告列表
	 * @param int $page 页码
	 * @param int $pagesize 每页数量
	 * @return array 广告数组
	 */
	public function fetch_all($page = 1, $pagesize = 10,$search_data = null, $expire_time = TIMESTAMP) {
		$where = array();
		$params = array($this->_table);

		if($search_data !== null) {
			foreach($search_data as $key => $value) {
				$allowed_keys = ['id', 'title', 'status', 'uid', 'position'];
				if(!in_array($key, $allowed_keys)) {
					continue;
				}
				if($value !== null && $value !== '' && $value!= 0) {
					if(is_int($value) || ctype_digit($value)) {
						$where[] = $key.'=%d';
					} else {
						$where[] = $key.'=%s';
					}
					$params[] = $value;
				}    
			}
		}
		
		if($expire_time != -1) {
			$where[] = '(expire_time IS NULL OR (expire_time > %d AND expire_time > %d))';
			$params[] = $expire_time;
			$params[] = TIMESTAMP;
		}
		$count_sql = "SELECT COUNT(*) FROM %t";
		if(!empty($where)) {
			$count_sql .= " WHERE " . implode(' AND ', $where);
		}
		$total = DB::result_first($count_sql, $params);

		$sql = "SELECT * FROM %t";

		if(!empty($where)) {
			$sql .= " WHERE " . implode(' AND ', $where);
		}

		$sql .= " ORDER BY sort ASC";

		if($page && $pagesize) {
			$start = ($page - 1) * $pagesize;
			$sql.= " LIMIT $start, $pagesize";	
		}

		$data = DB::fetch_all($sql, $params);

		return array(
			'data' => $data,
			'total' => $total
		);
	}

	/**
	 * 查询是否有未过期广告
	 * @param int $sort 广告位置
	 * @param int $status 广告状态
	 * @return array 广告数组
	 */
	public function fetch_by_sort_status($sort, $status, $id = 0) {
		$sql = "SELECT * FROM %t WHERE `sort`=%d";
		$params = array($this->_table, $sort);
		
		if(is_array($status)) {
			$sql .= " AND `status` IN (".implode(',', array_fill(0, count($status), '%d')).")";
			$params = array_merge($params, $status);
		} else {
			$sql .= " AND `status`=%d";
			$params[] = $status;
		}
		
		$sql .= " AND `expire_time`>%d";
		$params[] = TIMESTAMP;
		
		if($id) {
			$sql .= " AND `id`!=%d";
			$params[] = $id;
		}
		
		return DB::fetch_first($sql, $params);
	}
	
	/**
	 * 插入广告
	 * @param array $data 广告数据
	 * @return int 插入的广告ID
	 */
	public function insert($data, $return_insert_id = false, $replace = false, $silent = false, $unbuffered = false) {
		//在$data中添加创建时间
		$data['create_time'] = TIMESTAMP;
		if(DB::insert($this->_table, $data, $return_insert_id, $replace)) {
            return DB::insert_id();
        }
        return false;	
	}

	/**
	 * 更新广告
	 * @param int $id 广告ID
	 * @param array $data 要更新的数据
	 * @return bool 更新结果
	 */
	public function update($id, $data, $unbuffered = false, $low_priority = false) {
		return DB::update($this->_table, $data, array('id' => $id), $unbuffered, $low_priority);	
	}

	/**
     * 删除广告
     * @param int $id 广告ID
     * @param bool $unbuffered 是否无缓冲
     * @return bool 删除结果
     * @throws Exception 如果删除失败
     */
    public function delete($id, $unbuffered = false) {
		return DB::delete($this->_table, array('id' => $id), $unbuffered);
    }

	/**
	 * 审核通过
	 * @param int $id 广告ID
	 * @return bool 审核结果
	 */
	public function audit_pass($id) {
		$ad_info = DB::fetch_first("SELECT * FROM %t WHERE id=%d", array($this->_table, $id));
    
		$data = [
			'audit_time' => TIMESTAMP,
			'status' => 1,
		];
		
		if ($ad_info['status'] == 3) {
			$new_expire_time = $ad_info['expire_time'] + (TIMESTAMP - $ad_info['create_time']);
			$data['expire_time'] = $new_expire_time;
		}
		
		$result = DB::update($this->_table, $data, array('id' => $id));
		return $result ? true : false;
	}
}